<?php
namespace Operator\Model;

/**
 * 行程预览
 */
class OrderCenter2Model extends BaseModel
{
    /**
     * 行程预览页面信息详情
     */
    public function order()
    {
        $res     = [];
        $line_id = I('id');
        //线路信息与签证价格
        $line = M('public_line as l')
            ->field('line_id,insure_price_id,is_everyday,forum_time,line_name,start_time,end_time,money_type,go_price_id,back_price_id,trip_id,money_type,visa_price,sprice_id')
            ->where(['line_id' => $line_id])
            ->find();
        $operator_id = session('operator_user.pid') ? session('operator_user.pid') : session('operator_user.operator_id');

        //常规日期的价格
        $res['public_price'] = M('line_reseller_price')
            ->field('adult_price,child_price,oldman_price')
            ->where([
                'line_id' => $line_id,
                [
                    'rp_type' => 0,
                    [
                        'reseller_id' => $operator_id,
                        'rp_type'     => 1,
                    ],
                    '_logic'  => 'or',
                ],
            ])
            ->find();

        if ($line['is_everyday']) {
            $day = $this->getDateFromRange($line['start_time'], $line['end_time']);
        } else {
            $day = $this->getDateFromList($line['forum_time']);
        }

        //保险种类与价格
        $res['insure'] = M('line_upgrade_insure')
            ->field('up_insure_id,now_adult_price,now_child_price,insure_name')
            ->where(['line_id' => $line['line_id']])
            ->select();

        //行程文字简介详情
        $trip = M('public_trip')
            ->field('introduce')
            ->where(['trip_id' => ['in', $line['trip_id']]])
            ->select();

        //查询来回交通方式的名称
        $res['traffic'] = $this->getTraffic($line['go_price_id'], $line['back_price_id']);

        //特殊日期
        $res['special'] = M('operator_special_price')
            ->field('sprice_id,day,adult_price,child_price,oldman_price')
            ->where(['sprice_id' => ['in', $line['sprice_id']], 'day' => ['egt', date('Ymd', time())]])
            ->select();
        $res['trip'] = array_map('array_shift', $trip);
        $res['line'] = $line;

        foreach ($day as $v) {
            $res['time'][] = $v['time']; //日历上的开团时间字符串
            $res['word'][] = $v['word']; //行程详情
        }

        //行程可选酒店
        $res['hotel'] = $this->tripHotel($line_id);

        //查询线路关联的附加产品
        $res['add_product'] = $this->additionalProduct($line['line_id']);

        return $res;
    }

    /**
     * 获取行程酒店
     * @param  [int]   $line_id [线路id]
     * @return [array]          [行程酒店]
     */
    private function tripHotel($line_id)
    {
        $lodging = M('public_trip')
            ->field('lodging, current_day')
            ->where(['line_id' => $line_id])
            ->select();

        $m = M('public_single_supplier as s ');

        foreach ($lodging as $k => $v) {
            $hotel = $m
                ->field('supplier_name')
                ->join('__PUBLIC_SINGLE_ROOM_PRICE__ as p on p.supplier_id = s.supplier_id')
                ->where(['p.room_priceId' => ['in', $v['lodging']]])
                ->select();
            $lodging[$k]['hotel'] = implode('、', array_map('array_shift', $hotel));
        }
        return $lodging;
    }

    /**
     * 来回交通方式的名称
     * @param  [int]   $go_price_id   [出发的交通方式id]
     * @param  [int]   $back_price_id [回来的交通方式id]
     * @return [array]                [交通方式名称数组]
     */
    private function getTraffic($go_price_id, $back_price_id)
    {
        $m         = M('public_single_traffic_price as tp');
        $arr       = [];
        $arr['go'] = $m
            ->join(" __PUBLIC_SINGLE_TRAFFIC__ as t on tp.traffic_id = t.traffic_id and tp.traffic_priceId = '{$go_price_id}'")
            ->getField('traffic_name');

        $arr['back'] = $m
            ->join(" __PUBLIC_SINGLE_TRAFFIC__ as t on tp.traffic_id = t.traffic_id and tp.traffic_priceId = '{$back_price_id}'")
            ->getField('traffic_name');
        return $arr;
    }

    /**
     * 线路关联的附件产品
     * @param  [int]   $line_id [线路id]
     * @return [array]          [附加产品列表]
     */
    private function additionalProduct($line_id)
    {

        $res = M('line_additional_product')
            ->field('product_id,product_name,product_price')
            ->where(['line_id' => $line_id, 'is_show' => 1, 'is_delete' => 1])
            ->select();
        return $res;
    }

    /**
     * 获取线路行程详情
     */
    public function tripDetail()
    {

        $line_id = I('id');
        $res     = [];

        //线路详情
        $res['line'] = M('public_line')
            ->field('trip_id,line_name,group_num,go_price_id,back_price_id,origin_id,destination_id,theme_name')
            ->where(['line_id' => $line_id])
            ->find();

        //交通方式
        $res['traffic'] = $this->getTraffic($res['line']['go_price_id'], $res['line']['back_price_id']);

        $m = M('areas');
        //行程详情
        $res['trip'] = $this->trip($res['line']['trip_id']);

        //出发城市
        $res['set_out'] = $m
            ->where(['areaId' => $res['line']['origin_id']])
            ->getField('areaName');

        $dest_city = $m
            ->field('areaName')
            ->where(['areaId' => ['in', $res['line']['destination_id']]])
            ->select();
        $res['dest'] = implode(',', array_map('array_shift', $dest_city));
        return $res;
    }

    /**
     * 获取每天行程详情
     * @param string $trip 用,拼接的行程id
     * @return  array
     */
    private function trip($trip)
    {
        $trip = M('public_trip as t')
            ->where(['trip_id' => ['in', $trip]])
            ->order('current_day')
            ->select();

        //游玩项目id
        $play_id = implode(',', $this->array_cloumn($trip, 'play_id'));
        $play    = M('public_play')
            ->where(['play_id' => ['in', $play_id]])
            ->select();
        $play = $this->changeIndex($play);

        //购物项目
        $shop_id = implode(',', $this->array_cloumn($trip, 'shopping_id'));
        $shop    = M('public_shopping')
            ->where(['shopping_id' => ['in', $shop_id]])
            ->select();
        $shop = $this->changeIndex($shop);

        $m_suplier = M('public_single_supplier as s');
        foreach ($trip as $k => $v) {
            $content = [];

            $stay = $m_suplier
                ->field('supplier_name')
                ->join('__PUBLIC_SINGLE_ROOM_PRICE__ as p on p.supplier_id = s.supplier_id')
                ->where(['p.room_priceId' => ['in', $v['lodging']]])
                ->select();
            $trip[$k]['stay']         = implode(',', array_map('array_shift', $stay));
            $play_id                  = explode(',', $trip[$k]['play_id']);
            $shop_id                  = explode(',', $trip[$k]['shopping_id']);
            $trip[$k]['trip_details'] = html_entity_decode($v['trip_details']);
            foreach ($play_id as $v1) {
                if ($play[$v1]) {
                    $trip[$k]['play'][] = $play[$v1];
                    $content[]          = $play[$v1]['name'];
                }
            }
            foreach ($shop_id as $v2) {
                if ($shop[$v2]) {
                    $trip[$k]['shop'][] = $shop[$v2];
                }

            }
            $trip[$k]['trip_content'] = implode('——', $content);
        }
        return $trip;
    }

    /**
     * 查询所选天数的剩余游客位数
     */
    public function getSeat()
    {
        $line_id = I('line_id');
        $day     = I('day');
        $m       = M('day_seat');
        //查询日期座位表中有无记录
        $record = $m
            ->where(['line_id' => $line_id, 'day' => $day])
            ->getField('surplus_tourist');
        if (isset($record)) {
            return $record;
        }

        //新增记录
        $guests_num = M('public_line')
            ->where(['line_id' => $line_id])
            ->getField('guests_num');

        $res = $m
            ->data([
                'day'             => $day,
                'surplus_tourist' => $guests_num,
                'line_id'         => $line_id,
            ])
            ->add();

        return $guests_num;
    }

    /**
     * 查询当天剩余交通座位
     * @param int $line_id 线路id
     * @return array 交通价格数组
     */
    private function surplusSeat($line_id)
    {
        $surplus_seat = M('day_seat')->where(['day' => date('Ymd', time()), 'line_id' => $line_id])->getField('traffic_price');

        $surplus_seat = json_decode($surplus_seat, true);
        $key          = array_keys($surplus_seat);

        $info = M('public_single_traffic_price')
            ->field('seat_id')
            ->where(['traffic_priceId' => ['in', $key]])
            ->select();
        $seat_id = array_map('array_shift', $info);

        //座位名称
        $seat = M('public_single_traffic_seat as s')
            ->field('seat_id,seat_name,traffic_name')
            ->join('__PUBLIC_SINGLE_TRAFFIC__ as t on s.traffic_id = t.traffic_id')
            ->where(['seat_id' => ['in', $seat_id]])
            ->select();

        foreach ($seat as $k => $v) {
            if (isset($surplus_seat[$v['seat_id']])) {
                $seat[$k]['seat'] = $surplus_seat[$v['seat_id']];
            }
        }

        return $seat;
    }

    /**
     * 获取时间范围内的日期
     * @param  string  $list 出团时间表
     * @return [array]
     */
    private function getDateFromList($list)
    {
        $list = explode(',', $list);
        $time = strtotime(date('Y-m-d', time()));
        $date = [];
        $i    = 1;

        foreach ($list as $k => $v) {
            $v = strtotime($v);
            if ($v < $time) {
                continue;
            }

            $date[$i]['time'] = date('Ymd', $v);
            $date[$i]['word'] = "第{$i}天 "/*. date('Y-m-d', $v) . ' 星期' . mb_substr( '日一二三四五六',date('w',$v),1,'utf-8' )*/;
            $i++;
        }

        return $date;
    }

    /**
     * 获取时间范围内的日期
     * @param  [int] $start [开始时间戳]
     * @param  [int] $end   [结束时间戳]
     * @return [array]
     */
    private function getDateFromRange($start, $end)
    {
        $now_time = time();
        $start    = $start > $now_time ? $start : $now_time;
        // 计算日期段内有多少天
        $days = ($end - $start) / 86400 + 1;

        // 保存每天日期
        $date = array();

        for ($i = 0; $i < $days; $i++) {
            $time             = $start + (86400 * $i);
            $k                = $i + 1;
            $date[$i]['time'] = date('Ymd', $time);
            $date[$i]['word'] = "第{$k}天 " . date('Y-m-d', $time) . ' 星期' . mb_substr('日一二三四五六', date('w', $time), 1, 'utf-8');
        }

        return $date;
    }

    public function checkGroup()
    {
        $time   = I('day');
        $time   = strtotime(substr($time, 0, 4) . '-' . substr($time, 4, 2) . '-' . substr($time, 6, 2));
        $status = M('public_group')
            ->where(['line_id' => I('line_id'), 'out_time' => $time])
            ->getField('group_status');
        $this->checkTime($time);
        //状态2表明已经出团
        if ($status == 2 || $status === false) {
            return ['status' => -1, 'msg' => '已出团'];
        }

        return ['status' => 1, 'msg' => 'ok'];

    }

    /**
     * 检测出团时间
     * @param int, $[time] [<出团时间戳>]
     */
    private function checkTime($time)
    {
        $now_time = time();
        $line     = M('public_line')
            ->field('till_day,book_day,start_time,end_time,is_everyday,forum_time')
            ->where(['line_id' => I('line_id')])
            ->find();

        if( $now_time < ($time - 86400*$line['book_day'] ) ||  $now_time > ($time - 86400*$line['till_day'] + 86400) ){
            die(json_encode(['status' => -2, 'msg' => '不在所选出团日期的预订时间之内']));
        }
    }
}
